package main

import (
	"fmt"
	"sort"
	"strings"
)

// Q1: Given a string, you have to insert 'a' into it,
// subject to the condition that the string cannot contain 3
// consecutive a's. Return the maximum number of a's that can be inserted.
// For eg: dog: return 8, as you can make aadaaoaagaa.
func newString(s string) string {
	res := ""
	letters := strings.Split(s, "")

	for i := 0; i < len(letters); i++ {
		letter := letters[i]
		if letter != "a" {
			res = res + "aa" + letter
		} else {
			// letter == a
			cnt := 1
			for i+cnt < len(letters) && letters[i+cnt] == "a" {
				cnt++
			}

			if (i + cnt) < len(letters) {
				if cnt == 1 {
					res = res + "aa" + letters[i+cnt]
				} else if cnt >= 2 {
					res = res + "aa" + letters[i+cnt]
				}
			}

			i += cnt
			// if (i + cnt) >= len(letters) {

			// } else {

			// }
		}
	}

	res += "aa"
	return res
}

func deleteString(s string) string {
	letters := strings.Split(s, "")
	res := letters[0]
	for i := 1; i < len(letters); i++ {
		if letters[i] != letters[i-1] {
			res += letters[i]
		} else {
			cnt := 1
			//same letter
			for i+cnt < len(letters) && letters[i+cnt] == letters[i] {
				cnt++
			}
			if i+cnt < len(letters) {
				res = res + letters[i] + letters[i+cnt]
			} else {
				res = res + letters[i]
			}
			i += cnt
		}
		// fmt.Println(res)
	}
	return res
}

type WordCount struct {
	letter string
	count  int
}

func formatString(input map[string]int) string {
	res := ""
	total := 0
	aa := []WordCount{}
	for key, value := range input {
		total += value
		wc := WordCount{
			letter: key,
			count:  value,
		}
		aa = append(aa, wc)
	}
	sort.Slice(aa, func(i, j int) bool {
		return aa[i].count <= aa[j].count
	})
	// fmt.Println(aa)
	i := 0
	j := len(aa) - 1
	cnt := 0
	for len(res) != total {

		res += aa[j].letter
		aa[j].count--
		cnt++
		if aa[j].count == 0 {
			j--
			cnt = 0
		}
		if cnt == 2 && aa[j].count != 0 {
			res += aa[i].letter
			aa[i].count--
			cnt = 0
			if aa[i].count == 0 {
				i++
			}
		}

	}
	return res
}
func main() {
	s := "aaa"
	fmt.Println(newString(s))

	// s2 := "xxxtxxx"
	// fmt.Println(deleteString(s2))
	// input := map[string]int{
	// 	"A": 1,
	// 	"B": 2,
	// 	"C": 4,
	// }
	// fmt.Println(formatString(input))
}
